package com.bootcamp.servlet.cart;

/**
 * @program: wrok-1101
 * @author: Keyu Li
 * @create: 2021-11-04 21:58
 **/

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@WebServlet(name = "AddCartServlet", value = "/AddCartServlet")
public class AddCartServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        // 获取商品id及数量count
        Integer id = Integer.parseInt(request.getParameter("id"));
        Integer count = Integer.parseInt(request.getParameter("count"));
        String storepage = request.getContextPath() + "/ShopStoreServlet";
        // 如果count为非整数，则添加失败
        if (count<=0){
            response.getWriter().println("数量只能为正数！添加失败！正在跳转首页ing");
            response.setHeader("refresh", "1;url=" + storepage);
            return;
        }
        Map<Integer, Integer> newItem = new HashMap<Integer, Integer>();

        //添加到session中，使用map存储id和count的对应关系，本方法中不对id进行合法性校验
        HttpSession session = request.getSession();
        Map<Integer, Integer> cartItems = (Map<Integer, Integer>) session.getAttribute("cartItem");
        if (cartItems == null) {
            cartItems = new HashMap<Integer, Integer>();
            session.setAttribute("cartItem", cartItems);
        }
        Integer oldCount = cartItems.get(id);
        if (oldCount != null) {
            cartItems.put(id, count + oldCount);
        } else {
            cartItems.put(id, count);
        }
        // 添加成功后，跳转到首页
        response.getWriter().println("添加成功！正在跳转首页ing");
        response.setHeader("refresh", "1;url=" + storepage);
    }


    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
